# -*- coding:utf-8 –*-
import cv2
import pyzbar.pyzbar as pyzbar

screen_width=640
screen_height=480

cap = cv2.VideoCapture(0)     
cap.set(cv2.CAP_PROP_FRAME_WIDTH,screen_width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,screen_height)



def decodeDisplay(video):
    global barcodeData
    global flag_qr
    # 转为灰度图像
    gray = cv2.cvtColor(video, cv2.COLOR_BGR2GRAY)
    barcodes = pyzbar.decode(gray)
    for barcode in barcodes:
        # 提取二维码的位置, 然后用边框标识出来在视频中
        (x, y, w, h) = barcode.rect
        cv2.rectangle(video, (x, y), (x + w, y + h), (0, 255, 0), 2)
        # 字符串转换
        barcodeData = barcode.data.decode("utf-8")
        barcodeType = barcode.type
        
        # 在图像上面显示识别出来的内容
        text = "{}".format(barcodeData)
        cv2.putText(video, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,1, (0, 255, 0), 2)
        # 打印识别后的内容
        print("[扫描结果] 二维码类别： {0} 内容： {1}".format(barcodeType, barcodeData))
        flag_qr = 1
    cv2.imshow("cam", video)

flag_qr = 0
while 1:
    ret ,frame = cap.read()

    decodeDisplay(frame)

    if flag_qr == 1:
        print(barcodeData)

    cv2.imshow("f_r",frame)
    cv2.moveWindow('f_r',0,0)
    
    if cv2.waitKey(1) == 27:
        break

cap.release()
cv2.destroyAllWindows()